package com.replication.jdbc.connection;

public class MysqlConnectionSelector extends AbstructConnectionSelector {
    static final String[] MASTER_ONLY_SQLS = new String[]{"SELECT LAST_INSERT_ID()"};
    static final String HEARTBEAT_SQL = "SELECT 0";
    private boolean switchHeartbeat = false;

    public MysqlConnectionSelector() {
    }

    protected boolean isMasterOnly(String sql) {
        String upperSql = sql.trim().toUpperCase();
        String[] masterOnlySqls = MASTER_ONLY_SQLS;
        int count = MASTER_ONLY_SQLS.length;

        for(int i = 0; i < count; ++i) {
            String query = masterOnlySqls[i];
            if(query.equalsIgnoreCase(upperSql)) {
                return true;
            }
        }

        return "SELECT 0".equals(upperSql)?this.heatbeatSelect():!isSelectFrom(sql);
    }

    private boolean heatbeatSelect() {
        if(this.switchHeartbeat) {
            this.switchHeartbeat = false;
        } else {
            this.switchHeartbeat = true;
        }

        return this.switchHeartbeat;
    }
}
